/*
 * UpdateController.java
 *
 * Created on March 7, 2007, 9:20 AM
 */

package edu.byu.isys413.group1E.data;

import edu.byu.isys413.group1E.handlers.*;
import java.sql.*;
import java.util.ArrayList;

/** This class performs the business logic, to post the business objects from a
 *transaction to the tables in the DB.
 *
 * @author Travis Kulbeth
 */
public class UpdateController {
    
    /** Contains an instance of UpdateController*/
    private static UpdateController instance = null;
    
    /** Create a new instance of UpdateController */
    private UpdateController(){
        
    }
    
    /** Retrieves an instance of the TransLineDAO object
     *
     * @return a current instance of the UpdateController class
     */
    public static synchronized UpdateController getInstance() {
        if (instance == null) {
            instance = new UpdateController();
        }
        return instance;
    }
    
    /** Posts information to the system, performing the business logic and processes
     * Called when a transaction is complete
     * 
     * @param tx contains the TransactionBO object with the information 
     * to be written to the dB.
     */
    public synchronized void post_sale(TransactionBO tx){
        try {
            Connection conn = ConnectionPool.getInstance().get();
            try {
                ArrayList<TransLineBO> txLines = tx.getTxLineList();
                
                //populate the list with the revenue sources
                ArrayList<RevenueSourceBO> revSrcs = new ArrayList<RevenueSourceBO>();
                for(int x=0;x<txLines.size();x++){
                    revSrcs.add(txLines.get(x).getRevSrc());
                }
                
                //now save the revenue sources
                for(int j=0; j<revSrcs.size(); j++){
                    String type = revSrcs.get(j).getType();
                    if(type.equals("sale")){
                        //do the specific save operations for sale transactions here (like adjust inventory)
                        EmployeeDAO empDAO = EmployeeDAO.getInstance();
                        StoreDAO storeDAO = StoreDAO.getInstance();
                        EmployeeBO empBO = null;
                        StoreBO storeBO = null;
                        Session session = null;
                        try{
                            empBO = empDAO.read("0000011106a3cc390000007f000002");
                            storeBO = storeDAO.read("0000011106a3cc380000007f000002");
                            session = Session.create(tx.getEmployee(), tx.getStore());
                            SaleHandler.getInstance().postSale((SaleBO)revSrcs.get(j), session);
                        }catch(Exception e){
                            e.printStackTrace();
                        }                       
                    }//end sale
                    
                    //special case for the backup = update the backup size in the db.
                    if(type.equals("backup")){
                        try {   //add more backup space to the member's object
                            double curMembBuSize = tx.getCustomer().getCustMembership().getBuSize();
                            BackupBO bk = (BackupBO)revSrcs.get(j);
                            MembershipBO memb = tx.getCustomer().getCustMembership();
                            //if it's a new member purchasing storage space
                            if(memb.getBuExpDate() == null){
                                memb.setBuExpDate(bk.getEndDate());
                            }
                            memb.setBuSize(curMembBuSize + bk.getBuSize());
                            MembershipDAO.getInstance().save(memb, conn);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    
                    //any other specifically needed save procedures can be done with if statements like above here
                    //otherwise, if the revenue source is just a standard save procedure, save them using the factory
                    RSDAO_Factory.getInstance().getDAO(type).save(revSrcs.get(j));
                }//for loop to save
                //save the transaction (DAO.save)
                TransactionDAO.getInstance().save(tx, conn);
                //save payment
                if(tx.getTransStatus().equals("Complete")){
                    PaymentDAO.getInstance().save(tx.getPmt(), conn);
                }
                conn.commit();
                System.out.println("Arrived here in the update controller now.");
                //catch exceptions and rollback
            } catch (SQLException ex) {
                conn.rollback();
                throw new SQLException();
            } catch (DataException ex) {
                conn.rollback();
                ex.printStackTrace();
            } catch (ConnectionPoolException ex) {
                conn.rollback();
                ex.printStackTrace();
            }
            //release the connection
            ConnectionPool.getInstance().release(conn);
        } catch (SQLException ex){
            ex.printStackTrace();
            System.out.println("An error occurred saving transaction with id " + tx.getTransID());
        } catch (ConnectionPoolException ex) {
            ex.printStackTrace();
        }
        // update inventory
        //update accounts receivable
        //update total cash
    }
}
